
import api from '@/api/api.js'
import request from '@/common/request.js'

/*缓存数据*/
function $setStorageSync(key, data) {
	uni.setStorageSync(key, data);
}
/*获取缓存数据*/
function $getStorageSync(key) {
	let data = uni.getStorageSync(key);
	return data;
}
/*清除缓存数据*/
function $clearStorageSync(type) {
	uni.clearStorage();
	uni.clearStorageSync();
	if (type == 2) {
		this.$showToast('清除成功');
		this.$navigateTo('../login/login');
	} else if (type == 3) {
		this.$showToast('退出成功');
		this.$navigateTo('../login/login');
	} else {
		return;
	}
}
//弹框
function $showModel(title, content, callback) {
	uni.showModal({
		title: title,
		content: content,
		confirmColor: '#F7AC00',
		cancelColor: '#F7AC00',
		showCancel: false,
		success: function (res) {
			if (callback) {
				callback(res);
			}
		}
	})
}

function $showToast(title, callback, icon) {
	console.log(icon)
	uni.showToast({
		confirmColor: '#CF1322',
		cancelColor: '#CF1322',
		title: title,
		showCancel: false,
		icon: icon,
		mask: true,
		success: function (res) {
			if (callback) {
				callback(res);
			}
		}
	})
}
//navigateTo页面跳转保留当前页面，跳转到应用内的某个页面，使用uni.navigateBack可以返回到原页面
function $navigateTo(url) {
	console.log(url)
	uni.navigateTo({
		url: url
	});
}
//redirectTo关闭当前页面，跳转到应用内的某个页面
function $redirectTo(url) {
	console.log(url)
	uni.redirectTo({
		url: url
	});
}
//跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面。
function $switchTab(url) {
	uni.switchTab({
		url: url
	});
}
//关闭当前页面，返回上一页面或多级页面
function $navigateBack(delta) {
	uni.navigateBack({
		delta: delta
	});
}


//文件下载并预览
function $downFile(urlStr) {
	console.log('文件下载');
	console.log(urlStr);
	uni.showLoading({
		title: '加载中'
	});
	uni.downloadFile({
		url: urlStr,
		success(res) {
			var filePath = res.tempFilePath;
			//window.open(urlStr)
			uni.openDocument({
				filePath: filePath,
				success: function (res) {
					console.log('打开文档成功', res);
					uni.hideLoading();
				},fail() {
					console.log("22222")
					window.open(urlStr)
				}
			})
		},
		fail(res) {
			uni.hideLoading();
			uni.showToast({
				title: '下载失败' + JSON.stringify(res),
				duration: 3000

			});
		}
	});
}

function isNullStr(obj, errorstr) {
	if (obj) {
		return true;
	} else {
		this.$showToast(errorstr + '不能为空！', function () {
			return false;
		});
	}
}

function formatName(name) {
	var nameobj = name;
	if (nameobj) {
		nameobj = JSON.parse(name);
	}
	return nameobj;
}


//文件上传
function uploadImage(images, url, cb) {
console.log("token="+uni.getStorageSync("userInfo").token)
	uni.uploadFile({
		url: url, //仅为示例，非真实的接口地址
		filePath: images,
		name: 'file',
		header: {
			"X-Access-Token": uni.getStorageSync("userInfo").token
		},
		success: uploadFileRes => {
			uni.hideLoading();
			let temp = JSON.parse(uploadFileRes.data);

			if (cb) {
				cb(temp.message,temp)
			}
		}
	});

}

//扫码
function $scanCode(cb) {
	// 允许从相机和相册扫码
	let result = '';
	uni.scanCode({
		success: function (res) {
			console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);
			if (cb) {
				cb(res.result);
			}
		}
	});
}
//功能建设中弹框
function codeIng() {
	uni.showModal({
		confirmColor: '#CF1322',
		cancelColor: '#CF1322',
		showCancel: false,
		content: '功能建设中...'
	})
}
//时间切割
function parseTime(time) {
	if (time) {
		let t = time.substring(0, 10);
		return t;
	} else {
		return time;
	}
}
/**
 * 获取字典数组
 * @param dictCode 字典Code
 * @return List<Map>
 */
async function initDictOptions(dictCode) {
	if (!dictCode) {
		return '字典Code不能为空!';
	}
	//获取字典数组
	let res = await api.ajaxGetDictItems(dictCode);
	return res;
}

/**
 * 字典值替换文本通用方法
 * @param dictOptions  字典数组
 * @param text  字典值
 * @return String
 */
function filterDictText(dictOptions, text) {
	//--update-begin----author:sunjianlei---date:20191025------for:修复字典替换方法在字典没有加载完成之前报错的问题、修复没有找到字典时返回空值的问题---
	if (dictOptions instanceof Array) {
		for (let dictItem of dictOptions) {
			if (text === dictItem.value) {
				return dictItem.text
			}
		}
	}
	return text
	//--update-end----author:sunjianlei---date:20191025------for:修复字典替换方法在字典没有加载完成之前报错的问题、修复没有找到字典时返回空值的问题---
}

function getDictText(dictCode, text, val) {
	filterMultiDictText(dictCode, text).then(res => {
		val = res;
		console.log(val);
	});
}

/**
 * 字典值替换文本通用方法(多选)
 * @param dictOptions  字典数组
 * @param text  字典值
 * @return String
 */
async function filterMultiDictText(dictCode, text) {
	let dictOptions = await api.ajaxGetDictItems(dictCode);
	dictOptions = dictOptions.data.result;
	if (!text || !dictOptions || dictOptions.length == 0) {
		return ""
	}
	let re = "";
	let arr = text.split(",")
	dictOptions.forEach(function (option) {
		for (let i = 0; i < arr.length; i++) {
			if (arr[i] === option.value) {
				re += option.text + ",";
				break;
			}
		}
	});
	if (re == "") {
		return text;
	}
	return re.substring(0, re.length - 1);
}

/**
 * 翻译字段值对应的文本
 * @param children
 * @returns string
 */
async function ajaxFilterDictText(dictCode, key) {
	if (!dictCode) {
		return '字典Code不能为空!';
	}
	//console.log(`key : ${key}`);
	if (!key) {
		return '';
	}
	//通过请求读取字典文本
	let res = await request.globalRequest(`/sys/dict/getDictText/${dictCode}/${key}`, 'GET', {}, 1).then(function (res) {
		if (res.success) {
			console.log('restult: ' + res.result);
			return res.result;
		} else {
			return '';
		}
	})

}

function getNameImg(name) {
	console.log(name)
	if (name.length > 0) {
		name = name.substring(name.length - 2, name.length);
		return name;
	}
}

function getNameImg2(name) {
	console.log(name)
	if (name&&name.length > 0) {
		name = name.substring(0, 2);
		return name;
	}
}

function downLoad(filepath) {
	uni.downloadFile({
		url: this.$preView + filepath, //仅为示例，并非真实的资源
		success: (res) => {
			console.log(res);
			if (res.statusCode === 200) {
				console.log('下载成功');
			}
		}
	});
}
//获取文件名称
//适用于格式为  files/20200505/xxxxx_15019203123123.xxx
function getFileName(text) {
	if (!text || text.toString().split('/').length < 3 || text.toString().indexOf('_') === -1) {
		return text
	}
	let b = text.toString().substring(b.lastIndexOf('/'), b.length)

	//后缀
	let surfix = b.substring(b.lastIndexOf('.'), b.length)
	let c = b.substring(0, b.lastIndexOf('_'))
	return c + surfix
}

function currentDate() {
	let nowDate = new Date();
	let date = {
		year: nowDate.getFullYear(),
		month: nowDate.getMonth() + 1,
		date: nowDate.getDate()
	};

	let systemDate = date.year;
	if (date.month < 10) {
		systemDate += '-' + 0 + date.month;

	} else {
		systemDate += '-' + date.month;
	}

	if (date.date < 10) {
		systemDate += '-' + 0 + date.date;
	} else {
		systemDate += '-' + date.date;
	}

	return systemDate;
}

export default {
	$setStorageSync,
	$getStorageSync,
	$showModel,
	$showToast,
	$navigateTo,
	$redirectTo,
	$switchTab,
	$navigateBack,
	uploadImage, //图片上传方法的封装
	isNullStr, //非空验证
	$clearStorageSync, //清除缓存
	$downFile, //文件下载
	formatName,
	$scanCode,
	codeIng,
	parseTime,
	initDictOptions,
	filterDictText,
	filterMultiDictText,
	ajaxFilterDictText,
	getDictText,
	getNameImg, //获取文字头像
	getNameImg2, //获取文字头像前两个字
	downLoad, //文件下载
	getFileName,
	currentDate //获取当前时间
}